<template>
  <div class="warehouse-data-page">
    <!-- KPI指标卡片 -->
    <el-row :gutter="16" class="mb-3">
      <el-col :span="6">
        <el-card>
          <div class="kpi-title">当前库存量</div>
          <div class="kpi-value">{{ kpi.currentStock.toLocaleString() }}</div>
          <div class="kpi-subtitle">件商品</div>
          <div class="kpi-chart">
            <div class="utilization-info">
              <div class="utilization-progress">
                <div class="progress-label">库位使用率</div>
                <div class="progress-bar">
                  <div class="progress-fill" :style="{ width: kpi.stockUtilization + '%' }"></div>
                </div>
                <div class="progress-value">{{ kpi.stockUtilization }}%</div>
              </div>
              <div class="utilization-stats">
                <div class="stat-item">
                  <span class="stat-label">已用库位</span>
                  <span class="stat-value">{{ kpi.usedLocations }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">空闲库位</span>
                  <span class="stat-value">{{ kpi.freeLocations }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="kpi-title">今日入库量</div>
          <div class="kpi-value">{{ kpi.todayInbound.toLocaleString() }}</div>
          <div class="kpi-subtitle">件商品</div>
          <div class="kpi-chart">
            <div ref="inboundChartRef" style="height: 100px; width: 100%;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="kpi-title">今日出库量</div>
          <div class="kpi-value">{{ kpi.todayOutbound.toLocaleString() }}</div>
          <div class="kpi-subtitle">件商品</div>
          <div class="kpi-chart">
            <div ref="outboundChartRef" style="height: 100px; width: 100%;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="kpi-title">异常情况统计</div>
          <div class="kpi-value">{{ kpi.exceptionRate }}%</div>
          <div class="kpi-subtitle">异常率</div>
          <div class="kpi-chart">
            <div class="exception-stats">
              <div class="exception-item">
                <span class="exception-label">验货失败</span>
                <span class="exception-value">{{ kpi.inspectionFail }}</span>
              </div>
              <div class="exception-item">
                <span class="exception-label">错发/漏发</span>
                <span class="exception-value">{{ kpi.wrongShipment }}</span>
              </div>
              <div class="exception-item">
                <span class="exception-label">物流丢件</span>
                <span class="exception-value">{{ kpi.logisticsLost }}</span>
              </div>
              <div class="exception-item">
                <span class="exception-label">用户退款</span>
                <span class="exception-value">{{ kpi.userRefund }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="16" class="mb-3">
      <!-- 出入库趋势 -->
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>出入库趋势</h3>
            <div class="chart-controls">
              <el-date-picker
                v-model="chartDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleChartDateChange"
                style="width: 250px;"
              />
              <el-radio-group v-model="chartTimeUnit" @change="handleChartTimeUnitChange" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="year">年</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div ref="lineRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 发货渠道统计 -->
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>发货量</h3>
            <div class="chart-controls">
              <el-date-picker
                v-model="shipmentDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleShipmentDateChange"
                style="width: 250px;"
              />
              <el-radio-group v-model="shipmentTimeUnit" @change="handleShipmentTimeUnitChange" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="year">年</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div ref="barRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 员工打包统计 -->
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>员工打包统计</h3>
            <div class="chart-controls">
              <el-date-picker
                v-model="employeeDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleEmployeeDateChange"
                style="width: 250px;"
              />
            </div>
          </div>
          <div ref="employeeChartRef" class="employee-chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据统计 -->
    <el-card>
      <h4>详细数据统计</h4>
      
      <!-- 时间段搜索控制面板 -->
      <div class="search-panel mb-3">
        <div class="search-controls">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px;"
            @change="handleDateChange"
          />
          <el-button type="primary" size="small" @click="exportDetailData" style="margin-left: 12px;">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </div>
      
      <div class="table-actions">
        <span class="data-summary">统计时间：{{ currentTime }}</span>
      </div>
      <el-table :data="pagedDetailData" stripe style="width: 100%">
        <el-table-column prop="locationCode" label="库位编码" width="120" />
        <el-table-column prop="locationType" label="库位类型" width="100">
          <template #default="scope">
            <el-tag :type="getLocationTypeTagType(scope.row.locationType)" size="small">
              {{ scope.row.locationType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inCount" label="今日入库" width="100" />
        <el-table-column prop="outCount" label="今日出库" width="100" />
        <el-table-column prop="currentStock" label="当前库存" width="100" />
        <el-table-column prop="maxCapacity" label="最大容量" width="100" />
        <el-table-column prop="utilization" label="使用率" width="100">
          <template #default="scope">
            <div class="utilization-cell">
              <span>{{ scope.row.utilization }}%</span>
              <div class="utilization-bar">
                <div class="utilization-fill" :style="{ width: scope.row.utilization + '%' }"></div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getLocationStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdate" label="最后更新" width="150" />
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="detailPage.current"
        v-model:page-size="detailPage.size"
        :total="detailData.length"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px; text-align: right;"
        @size-change="handleDetailPageSizeChange"
        @current-change="handleDetailPageChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Download } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import * as XLSX from 'xlsx'; // 导入XLSX库

// 响应式数据
const dateRange = ref(['2024-08-01', '2024-08-14']);
// 图表日期范围
const chartDateRange = ref(['2024-08-01', '2024-08-14']);
const shipmentDateRange = ref(['2024-08-01', '2024-08-14']);
const employeeDateRange = ref(['2024-08-01', '2024-08-14']);

// 图表时间单位
const chartTimeUnit = ref('day'); // day, month, year
const shipmentTimeUnit = ref('day'); // day, month, year

// 员工姓名列表
const packagers = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];

// 当前时间
const currentTime = ref(new Date().toLocaleString('zh-CN'));

// 方法
const handleDateChange = () => {
  // 日期变化时自动更新数据
  updateDetailDataByDateRange();
};

const handleChartDateChange = () => {
  // 图表日期变化时自动更新图表
  if (chartDateRange.value && chartDateRange.value.length === 2) {
    const startDate = new Date(chartDateRange.value[0]);
    const endDate = new Date(chartDateRange.value[1]);
    const daysDiff = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1; // 包含开始和结束日期
    
    // 生成对应时间范围的数据
    const chartData = generateMockData(daysDiff);
    
    // 只更新出入库趋势图表，不影响KPI卡片中的趋势图
    if (lineChart) {
      lineChart.setOption({
        xAxis: { data: chartData.charts.line.dates },
        series: [
          { data: chartData.charts.line.inData },
          { data: chartData.charts.line.outData }
        ]
      });
    }
  }
};

const handleShipmentDateChange = () => {
  // 发货渠道统计日期变化时自动更新图表
  if (shipmentDateRange.value && shipmentDateRange.value.length === 2) {
    const startDate = new Date(shipmentDateRange.value[0]);
    const endDate = new Date(shipmentDateRange.value[1]);
    const daysDiff = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1; // 包含开始和结束日期
    
    // 根据时间段长度决定图表类型
    if (daysDiff > 1) {
      // 长时间段：显示分组柱状图（按渠道分组）
      const timeLabels = generateSmartDateLabels(shipmentDateRange.value[0], shipmentDateRange.value[1], shipmentTimeUnit.value);
      const timeSeriesData = generateTimeSeriesShipmentData(daysDiff, shipmentTimeUnit.value);
      
      // 为每个渠道创建系列
      const seriesData: any[] = [];
      const allChannels = ['日本邮政EMS', '航空', '海运', 'DHL', '日本国内', '直通', '直邮'];
      
      allChannels.forEach(channel => {
        const channelIndex = timeSeriesData.findIndex(item => item.channel === channel);
        if (channelIndex >= 0) {
          const channelData = timeSeriesData[channelIndex];
          
          // 为每个渠道创建系列
          seriesData.push({
            name: channel,
            type: 'bar',
            data: channelData.data,
            itemStyle: { color: getChannelColor(channel) },
            emphasis: {
              focus: 'series'
            }
          });
        }
      });
      
      // 添加总计系列
      const totalData = timeLabels.map((_, timeIndex) => {
        let total = 0;
        allChannels.forEach(channel => {
          const channelIndex = timeSeriesData.findIndex(item => item.channel === channel);
          if (channelIndex >= 0) {
            total += timeSeriesData[channelIndex].data[timeIndex] || 0;
          }
        });
        return total;
      });
      
      seriesData.push({
        name: '总计',
        type: 'line',
        data: totalData,
        itemStyle: { color: '#ff6b6b' },
        lineStyle: { width: 3, type: 'solid' },
        symbol: 'circle',
        symbolSize: 6,
        smooth: true
      });
      
      barChart = echarts.init(barRef.value);
      barChart.setOption({
        tooltip: { 
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          confine: true, // 确保tooltip不会超出容器边界
          position: function (point: any, params: any, dom: any, rect: any, size: any) {
            // 智能定位tooltip，避免被截断
            const [x, y] = point;
            const [width, height] = size.contentSize;
            const viewWidth = dom.clientWidth;
            const viewHeight = dom.clientHeight;
            
            let posX = x + 10;
            let posY = y - height - 10;
            
            // 如果右侧空间不够，显示在左侧
            if (posX + width > viewWidth) {
              posX = x - width - 10;
            }
            
            // 如果上方空间不够，显示在下方
            if (posY < 0) {
              posY = y + 10;
            }
            
            return [posX, posY];
          },
          formatter: function(params: any) {
            let result = params[0].axisValue + '<br/>';
            let total = 0;
            
            params.forEach((param: any) => {
              if (param.seriesName !== '总计') {
                result += param.marker + param.seriesName + ': ' + param.value + '<br/>';
                total += param.value;
              }
            });
            
            result += '<hr/>总计: ' + total;
            return result;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 12
          },
          extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.15); max-width: 300px;'
        },
        legend: { 
          data: seriesData.map(s => s.name),
          top: 15,
          type: 'scroll',
          textStyle: {
            color: '#666',
            fontSize: 12
          },
          itemGap: 15
        },
        grid: {
          left: '3%',
          right: '8%',
          bottom: '15%',
          top: '30%',
          containLabel: true
        },
        xAxis: { 
          type: 'category', 
          data: timeLabels,
          axisLabel: { 
            interval: Math.max(1, Math.floor(timeLabels.length / 10)),
            rotate: timeLabels.length > 15 ? 45 : 0,
            fontSize: 10,
            color: '#666'
          },
          axisTick: {
            alignWithLabel: true
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          }
        },
        yAxis: { 
          type: 'value',
          name: '发货量',
          nameTextStyle: {
            color: '#666'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: seriesData
      });
    } else {
      // 短时间段：显示渠道分布图
      const shipmentData = generateShipmentData(daysDiff);
      const xAxisData = shipmentData.map(item => item.channel);
      const seriesData: any[] = [];
      
      // 获取所有物流方式
      const allLogistics = ['日本邮政EMS', '航空', '海运', 'DHL'];
      
      // 为每个物流方式创建系列
      allLogistics.forEach(logistic => {
        const series = {
          name: logistic,
          type: 'bar',
          data: shipmentData.map(channel => {
            const logisticIndex = channel.logistics.indexOf(logistic);
            return logisticIndex >= 0 ? channel.data[logisticIndex] : 0;
          }),
          itemStyle: {
            color: getLogisticColor(logistic)
          }
        };
        seriesData.push(series);
      });
      
      // 更新图表
      if (barChart) {
        barChart.setOption({
          xAxis: { 
            data: xAxisData,
            axisLabel: { 
              interval: Math.max(1, Math.floor(xAxisData.length / 10)),
              rotate: xAxisData.length > 15 ? 45 : 0,
              fontSize: 10
            }
          },
          series: seriesData
        });
      }
    }
  }
};

const updateDetailDataByDateRange = async () => {
  // 模拟根据时间范围获取详细数据
  const startDate = new Date(dateRange.value[0]);
  const endDate = new Date(dateRange.value[1]);
  const daysDiff = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 1000));
  
  // 生成动态详细数据
  const locationTypes = ['普通库位', '冷库', '危险品库位', '高架库位', '地面库位'];
  const locationStatuses = ['可用', '占用', '锁定', '禁用'];
  
  const locations = [];
  for (let i = 1; i <= 20; i++) {
    const locationType = locationTypes[Math.floor(Math.random() * locationTypes.length)];
    const maxCapacity = [1000, 1500, 2000, 2500, 3000][Math.floor(Math.random() * 5)];
    const currentStock = Math.floor(Math.random() * maxCapacity);
    const utilization = Math.floor((currentStock / maxCapacity) * 100);
    const status = locationStatuses[Math.floor(Math.random() * locationStatuses.length)];
    
    locations.push({
      locationCode: `${String.fromCharCode(65 + Math.floor(i / 10))}${String(i % 10).padStart(2, '0')}`,
      locationType,
      currentStock,
      maxCapacity,
      utilization,
      inCount: Math.floor(Math.random() * 200) + 50,
      outCount: Math.floor(Math.random() * 150) + 30,
      status,
      lastUpdate: new Date(Date.now() - Math.floor(Math.random() * 24 * 60 * 60 * 1000)).toISOString().slice(0, 19).replace('T', ' ')
    });
  }
  
  detailData.value = locations;
  
  // 更新当前时间显示
  currentTime.value = new Date().toLocaleString('zh-CN');
};

// KPI数据
const kpi = ref({
  currentStock: 12500,
  todayInbound: 1200,
  todayOutbound: 1000,
  stockUtilization: 82,
  usedLocations: 1500,
  freeLocations: 500,
  exceptionRate: 1.2,
  inspectionFail: 50,
  wrongShipment: 30,
  logisticsLost: 20,
  userRefund: 10
});

// 详细数据
const detailData = ref([
  { locationCode: 'A001', locationType: '普通库位', inCount: 100, outCount: 80, currentStock: 1200, maxCapacity: 2000, utilization: 60, status: '可用', lastUpdate: '2024-08-14 10:30' },
  { locationCode: 'B002', locationType: '冷库', inCount: 50, outCount: 40, currentStock: 500, maxCapacity: 1000, utilization: 50, status: '占用', lastUpdate: '2024-08-14 11:00' },
  { locationCode: 'C003', locationType: '普通库位', inCount: 70, outCount: 65, currentStock: 800, maxCapacity: 1500, utilization: 53, status: '锁定', lastUpdate: '2024-08-14 11:30' }
]);

// 分页数据
const detailPage = ref({
  current: 1,
  size: 10
});

// 分页后的详细数据
const pagedDetailData = computed(() => {
  const start = (detailPage.value.current - 1) * detailPage.value.size;
  const end = start + detailPage.value.size;
  return detailData.value.slice(start, end);
});

// 图表引用
const lineRef = ref<HTMLElement>();
const barRef = ref<HTMLElement>();
const inboundChartRef = ref<HTMLElement>();
const outboundChartRef = ref<HTMLElement>();

// 图表实例
let lineChart: echarts.ECharts | null = null;
let barChart: echarts.ECharts | null = null;
let inboundChart: echarts.ECharts | null = null;
let outboundChart: echarts.ECharts | null = null;

// 计算属性
const dateRangeText = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    return `${dateRange.value[0]} 至 ${dateRange.value[1]}`;
  }
  return '请选择时间范围';
});

// 方法
const exportDetailData = () => {
  try {
    // 准备导出数据
    const exportData = detailData.value.map(item => ({
      '库位编码': item.locationCode,
      '库位类型': item.locationType,
      '今日入库': item.inCount,
      '今日出库': item.outCount,
      '当前库存': item.currentStock,
      '最大容量': item.maxCapacity,
      '使用率': item.utilization + '%',
      '状态': item.status,
      '最后更新': item.lastUpdate
    }));

    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    
    // 设置列宽
    const colWidths = [
      { wch: 12 }, // 库位编码
      { wch: 10 }, // 库位类型
      { wch: 10 }, // 当前库存
      { wch: 10 }, // 最大容量
      { wch: 10 }, // 使用率
      { wch: 10 }, // 入库数量
      { wch: 10 }, // 出库数量
      { wch: 10 }, // 周转天数
      { wch: 8 },  // 状态
      { wch: 20 }  // 最后更新
    ];
    ws['!cols'] = colWidths;

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '库位详细数据');

    // 生成文件名
    const startDate = dateRange.value[0] || '2024-08-01';
    const endDate = dateRange.value[1] || '2024-08-14';
    const fileName = `仓储库位详细数据_${startDate}_${endDate}.xlsx`;

    // 导出文件
    XLSX.writeFile(wb, fileName);
    
    ElMessage.success(`数据导出成功：${fileName}`);
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('数据导出失败，请重试');
  }
};

const generateMockData = (days: number) => {
  // 根据天数生成模拟数据
  const baseStock = 10000 + Math.floor(Math.random() * 5000);
  const baseUtilization = 75 + Math.floor(Math.random() * 20);
  
  // 生成按时间段统计的出入库数据（2小时为一个时间段）
  const timeSegments = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00'];
  const inboundData = generateTimeSegmentData(6, 30, 20); // 6个时间段，基础值30，变化范围20
  const outboundData = generateTimeSegmentData(6, 25, 15); // 6个时间段，基础值25，变化范围15
  
  // 生成库位数据
  const locationTypes = ['普通库位', '冷库', '危险品库位', '高架库位', '地面库位'];
  const locationStatuses = ['可用', '占用', '锁定', '禁用'];
  
  const generateLocationData = () => {
    const locations = [];
    for (let i = 1; i <= 20; i++) { // 生成20个库位
      const locationType = locationTypes[Math.floor(Math.random() * locationTypes.length)];
      const maxCapacity = [1000, 1500, 2000, 2500, 3000][Math.floor(Math.random() * 5)];
      const currentStock = Math.floor(Math.random() * maxCapacity);
      const utilization = Math.floor((currentStock / maxCapacity) * 100);
      const status = locationStatuses[Math.floor(Math.random() * locationStatuses.length)];
      
      locations.push({
        locationCode: `${String.fromCharCode(65 + Math.floor(i / 10))}${String(i % 10).padStart(2, '0')}`,
        locationType,
        inCount: Math.floor(Math.random() * 200) + 50,
        outCount: Math.floor(Math.random() * 150) + 30,
        currentStock,
        maxCapacity,
        utilization,
        status,
        lastUpdate: new Date(Date.now() - Math.floor(Math.random() * 24 * 60 * 60 * 1000)).toISOString().slice(0, 19).replace('T', ' ')
      });
    }
    return locations;
  };
  
  return {
    kpi: {
      currentStock: baseStock,
      todayInbound: inboundData.reduce((sum, val) => sum + val, 0), // 今日总入库量
      todayOutbound: outboundData.reduce((sum, val) => sum + val, 0), // 今日总出库量
      stockUtilization: baseUtilization,
      usedLocations: Math.floor(baseStock * 0.6), // 模拟已用库位
      freeLocations: Math.floor(baseStock * 0.4), // 模拟空闲库位
      exceptionRate: 1.0 + Math.floor(Math.random() * 2), // 模拟异常率
      inspectionFail: Math.floor(baseStock * 0.005), // 模拟验货失败
      wrongShipment: Math.floor(baseStock * 0.003), // 模拟错发/漏发
      logisticsLost: Math.floor(baseStock * 0.002), // 模拟物流丢件
      userRefund: Math.floor(baseStock * 0.001) // 模拟用户退款
    },
    detail: generateLocationData(),
    charts: {
      line: {
        dates: days > 1 ? generateSmartDateLabels(chartDateRange.value[0], chartDateRange.value[1], chartTimeUnit.value) : timeSegments,
        inData: days > 1 ? generateAggregatedData(chartDateRange.value[0], chartDateRange.value[1], 100, 50, chartTimeUnit.value) : inboundData,
        outData: days > 1 ? generateAggregatedData(chartDateRange.value[0], chartDateRange.value[1], 80, 40, chartTimeUnit.value) : outboundData
      },
      bar: {
        channels: [
          { name: '中国国内', logistics: ['日本邮政EMS', '航空', '海运', 'DHL'] },
          { name: '直通', logistics: ['航空', '海运'] },
          { name: '直邮', logistics: ['日本邮政EMS', '航空', 'DHL'] },
          { name: '日本国内', logistics: ['日本邮政EMS', '航空', '海运'] }
        ],
        shipmentCount: generateShipmentData(days),
        timeLabels: days > 1 ? generateSmartDateLabels(shipmentDateRange.value[0], shipmentDateRange.value[1], shipmentTimeUnit.value) : [],
        timeSeriesData: generateTimeSeriesShipmentData(days, shipmentTimeUnit.value)
      }
    }
  };
};

// 根据时间单位生成智能日期标签
const generateSmartDateLabels = (startDate: string, endDate: string, timeUnit: string = 'day') => {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
  
  const labels = [];
  
  if (timeUnit === 'year') {
    // 按年显示
    const startYear = start.getFullYear();
    const endYear = end.getFullYear();
    for (let year = startYear; year <= endYear; year++) {
      labels.push(`${year}年`);
    }
  } else if (timeUnit === 'month') {
    // 按月显示
    let current = new Date(start);
    while (current <= end) {
      const month = current.getMonth() + 1;
      const year = current.getFullYear();
      labels.push(`${year}年${month}月`);
      current.setMonth(current.getMonth() + 1);
    }
  } else {
    // 按日显示
    let current = new Date(start);
    while (current <= end) {
      const month = current.getMonth() + 1;
      const date = current.getDate();
      labels.push(`${month}月${date}日`);
      current.setDate(current.getDate() + 1);
    }
  }
  
  return labels;
};

// 根据时间单位生成聚合数据
const generateAggregatedData = (startDate: string, endDate: string, baseValue: number, variation: number, timeUnit: string = 'day') => {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
  
  const data = [];
  
  if (timeUnit === 'year') {
    // 按年聚合
    const startYear = start.getFullYear();
    const endYear = end.getFullYear();
    for (let year = startYear; year <= endYear; year++) {
      const yearValue = baseValue + Math.floor(Math.random() * variation * 2) - variation;
      data.push(Math.max(0, yearValue));
    }
  } else if (timeUnit === 'month') {
    // 按月聚合
    let current = new Date(start);
    while (current <= end) {
      const monthValue = baseValue + Math.floor(Math.random() * variation * 2) - variation;
      data.push(Math.max(0, monthValue));
      current.setMonth(current.getMonth() + 1);
    }
  } else {
    // 按日聚合
    let current = new Date(start);
    while (current <= end) {
      const dayValue = baseValue + Math.floor(Math.random() * variation * 2) - variation;
      data.push(Math.max(0, dayValue));
      current.setDate(current.getDate() + 1);
    }
  }
  
  return data;
};

const generateDateLabels = (days: number) => {
  // 使用通用的智能时间标签生成函数
  return generateSmartDateLabels(chartDateRange.value[0], chartDateRange.value[1]);
};

const generateRecentDates = (days: number) => {
  const dates = [];
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days + 1); // 确保日期是当前范围内的
  
  for (let i = 0; i < days; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);
    dates.push(`${date.getMonth() + 1}-${date.getDate().toString().padStart(2, '0')}`);
  }
  return dates;
};

const generateTimeSegmentData = (segments: number, baseValue: number, variation: number) => {
  const data = [];
  for (let i = 0; i < segments; i++) {
    // 根据时间段调整基础值，模拟业务规律
    let timeMultiplier = 1;
    if (i === 0) timeMultiplier = 0.8; // 8:00 刚开始，量较少
    else if (i === 1) timeMultiplier = 1.2; // 10:00 上午高峰
    else if (i === 2) timeMultiplier = 1.5; // 12:00 中午高峰
    else if (i === 3) timeMultiplier = 1.3; // 14:00 下午开始
    else if (i === 4) timeMultiplier = 1.4; // 16:00 下午高峰
    else if (i === 5) timeMultiplier = 0.6; // 18:00 接近下班，量减少
    
    const adjustedBase = baseValue * timeMultiplier;
    const randomVariation = Math.floor(Math.random() * variation * 2 - variation);
    data.push(Math.max(0, Math.floor(adjustedBase + randomVariation)));
  }
  return data;
};

const generateShipmentData = (days: number) => {
  const channelStructure = [
    { name: '中国国内', logistics: ['日本邮政EMS', '航空', '海运', 'DHL'] },
    { name: '直通', logistics: ['航空', '海运'] },
    { name: '直邮', logistics: ['日本邮政EMS', '航空', 'DHL'] },
    { name: '日本国内', logistics: ['日本邮政EMS', '航空', '海运'] }
  ];
  
  const data = [];
  
  // 为每个渠道生成发货量数据
  for (let i = 0; i < channelStructure.length; i++) {
    const channel = channelStructure[i];
    const channelData = [];
    
    // 为每个物流方式生成数据
    for (let j = 0; j < channel.logistics.length; j++) {
      let baseValue = 0;
      let variation = 0;
      
      // 不同物流方式的基础发货量和变化范围
      switch (channel.logistics[j]) {
        case '日本邮政EMS':
          baseValue = 85;
          variation = 30;
          break;
        case '航空':
          baseValue = 120;
          variation = 40;
          break;
        case '海运':
          baseValue = 65;
          variation = 25;
          break;
        case 'DHL':
          baseValue = 95;
          variation = 35;
          break;
      }
      
      // 根据时间范围调整发货量
      let timeMultiplier = 1.0;
      if (days > 7) {
        timeMultiplier = 1.2; // 长时间范围，发货量增加
      } else if (days > 3) {
        timeMultiplier = 1.1; // 中等时间范围
      } else {
        timeMultiplier = 1.0; // 短时间范围
      }
      
      const adjustedBase = baseValue * timeMultiplier;
      const randomVariation = Math.floor(Math.random() * variation * 2 - variation);
      channelData.push(Math.max(0, Math.floor(adjustedBase + randomVariation)));
    }
    
    data.push({
      channel: channel.name,
      logistics: channel.logistics,
      data: channelData
    });
  }
  
  return data;
};

// 生成时间系列发货数据
const generateTimeSeriesShipmentData = (days: number, timeUnit: string = 'day') => {
  const channelStructure = [
    { name: '日本邮政EMS', logistics: ['日本邮政EMS'] },
    { name: '航空', logistics: ['航空'] },
    { name: '海运', logistics: ['海运'] },
    { name: 'DHL', logistics: ['DHL'] },
    { name: '日本国内', logistics: ['日本国内'] },
    { name: '直通', logistics: ['直通'] },
    { name: '直邮', logistics: ['直邮'] }
  ];
  
  const timeSeriesData: Array<{
    channel: string;
    logistics: string[];
    data: number[];
  }> = [];
  
  channelStructure.forEach(channel => {
    const channelData = {
      channel: channel.name,
      logistics: channel.logistics,
      data: [] as number[]
    };
    
    if (timeUnit === 'year') {
      // 按年生成数据
      const years = Math.max(1, Math.ceil(days / 365));
      for (let year = 0; year < years; year++) {
        const yearValue = Math.floor(Math.random() * 1000) + 500;
        channelData.data.push(yearValue);
      }
    } else if (timeUnit === 'month') {
      // 按月生成数据
      const months = Math.max(1, Math.ceil(days / 30));
      for (let month = 0; month < months; month++) {
        const monthValue = Math.floor(Math.random() * 300) + 150;
        channelData.data.push(monthValue);
      }
    } else {
      // 按日生成数据
      for (let day = 0; day < days; day++) {
        const dayValue = Math.floor(Math.random() * 100) + 50;
        channelData.data.push(dayValue);
      }
    }
    
    timeSeriesData.push(channelData);
  });
  
  return timeSeriesData;
};

const updateCharts = (data: any) => {
  // 更新折线图
  if (lineChart) {
    lineChart.setOption({
      xAxis: { data: data.charts.line.dates },
      series: [
        { data: data.charts.line.inData },
        { data: data.charts.line.outData }
      ]
    });
  }
  
  // 更新柱状图
  if (barChart) {
    barChart.setOption({
      xAxis: { data: data.charts.bar.channels },
      series: [{
        data: data.charts.bar.shipmentCount.map((v: number) => parseFloat(v.toFixed(1)))
      }]
    });
  }
};

const initCharts = () => {
  // 生成初始数据，使用图表日期范围
  const days = chartDateRange.value && chartDateRange.value.length === 2 ? 
    Math.ceil((new Date(chartDateRange.value[1]).getTime() - new Date(chartDateRange.value[0]).getTime()) / (1000 * 60 * 60 * 24)) + 1 : 7;
  const initialData = generateMockData(days);
  
  // 出入库趋势折线图
  lineChart = echarts.init(lineRef.value);
  lineChart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['入库', '出库'] },
    xAxis: { type: 'category', data: initialData.charts.line.dates },
    yAxis: { type: 'value' },
    series: [
      { name: '入库', type: 'line', data: initialData.charts.line.inData },
      { name: '出库', type: 'line', data: initialData.charts.line.outData }
    ]
  });
  
  // 发货渠道统计图表
  const shipmentDays = shipmentDateRange.value && shipmentDateRange.value.length === 2 ? 
    Math.ceil((new Date(shipmentDateRange.value[1]).getTime() - new Date(shipmentDateRange.value[0]).getTime()) / (1000 * 60 * 60 * 24)) + 1 : 7;
  const shipmentData = generateShipmentData(shipmentDays);
  
  // 长时间段：显示分组柱状图（按渠道分组）
  const timeLabels = generateSmartDateLabels(shipmentDateRange.value[0], shipmentDateRange.value[1], shipmentTimeUnit.value);
  const timeSeriesData = generateTimeSeriesShipmentData(shipmentDays, shipmentTimeUnit.value);
  
  // 为每个渠道创建系列
  const seriesData: any[] = [];
  const allChannels = ['日本邮政EMS', '航空', '海运', 'DHL', '日本国内', '直通', '直邮'];
  
  allChannels.forEach(channel => {
    const channelIndex = timeSeriesData.findIndex(item => item.channel === channel);
    if (channelIndex >= 0) {
      const channelData = timeSeriesData[channelIndex];
      
      // 为每个渠道创建堆叠系列
      seriesData.push({
        name: channel,
        type: 'bar',
        data: channelData.data,
        itemStyle: { color: getChannelColor(channel) },
        stack: 'total', // 堆叠显示
        emphasis: {
          focus: 'series'
        }
      });
    }
  });
  
  // 添加总计系列
  const totalData = timeLabels.map((_, timeIndex) => {
    let total = 0;
    allChannels.forEach(channel => {
      const channelIndex = timeSeriesData.findIndex(item => item.channel === channel);
      if (channelIndex >= 0) {
        total += timeSeriesData[channelIndex].data[timeIndex] || 0;
      }
    });
    return total;
  });
  
  seriesData.push({
    name: '总计',
    type: 'line',
    data: totalData,
    itemStyle: { color: '#ff6b6b' },
    lineStyle: { width: 3, type: 'solid' },
    symbol: 'circle',
    symbolSize: 6,
    smooth: true
  });
  
  barChart = echarts.init(barRef.value);
  barChart.setOption({
    tooltip: { 
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      confine: true, // 确保tooltip不会超出容器边界
      position: function (point: any, params: any, dom: any, rect: any, size: any) {
        // 智能定位tooltip，避免被截断
        const [x, y] = point;
        const [width, height] = size.contentSize;
        const viewWidth = dom.clientWidth;
        const viewHeight = dom.clientHeight;
        
        let posX = x + 10;
        let posY = y - height - 10;
        
        // 如果右侧空间不够，显示在左侧
        if (posX + width > viewWidth) {
          posX = x - width - 10;
        }
        
        // 如果上方空间不够，显示在下方
        if (posY < 0) {
          posY = y + 10;
        }
        
        return [posX, posY];
      },
      formatter: function(params: any) {
        let result = params[0].axisValue + '<br/>';
        let total = 0;
        
        params.forEach((param: any) => {
          if (param.seriesName !== '总计') {
            result += param.marker + param.seriesName + ': ' + param.value + '<br/>';
            total += param.value;
          }
        });
        
        result += '<hr/>总计: ' + total;
        return result;
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.15); max-width: 300px;'
    },
    legend: { 
      data: seriesData.map(s => s.name),
      top: 15,
      type: 'scroll',
      textStyle: {
        color: '#666',
        fontSize: 12
      },
      itemGap: 15
    },
    grid: {
      left: '3%',
      right: '8%',
      bottom: '15%',
      top: '30%',
      containLabel: true
    },
    xAxis: { 
      type: 'category', 
      data: timeLabels,
      axisLabel: { 
        interval: Math.max(1, Math.floor(timeLabels.length / 10)),
        rotate: timeLabels.length > 15 ? 45 : 0,
        fontSize: 10,
        color: '#666'
      },
      axisTick: {
        alignWithLabel: true
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    yAxis: { 
      type: 'value',
      name: '发货量',
      nameTextStyle: {
        color: '#666'
      },
      axisLabel: {
        formatter: '{value}',
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0'
        }
      }
    },
    series: seriesData
  });

  // 入库折线图（KPI卡片）
  inboundChart = echarts.init(inboundChartRef.value);
  const kpiTrendData = generateKPITrendData();
  inboundChart.setOption({
    tooltip: { 
      trigger: 'axis',
      formatter: '{b}: {c} 件'
    },
    xAxis: { 
      type: 'category', 
      data: kpiTrendData.timeSegments,
      show: true,
      axisLabel: { fontSize: 10 }
    },
    yAxis: { 
      type: 'value',
      show: true,
      axisLabel: { fontSize: 10 }
    },
    series: [{
      name: '入库',
      type: 'line',
      data: kpiTrendData.inboundData,
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      lineStyle: { color: '#67C23A' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ]
        }
      }
    }]
  });

  // 出库折线图（KPI卡片）
  outboundChart = echarts.init(outboundChartRef.value);
  outboundChart.setOption({
    tooltip: { 
      trigger: 'axis',
      formatter: '{b}: {c} 件'
    },
    xAxis: { 
      type: 'category', 
      data: kpiTrendData.timeSegments,
      show: true,
      axisLabel: { fontSize: 10 }
    },
    yAxis: { 
      type: 'value',
      show: true,
      axisLabel: { fontSize: 10 }
    },
    series: [{
      name: '出库',
      type: 'line',
      data: kpiTrendData.outboundData,
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      lineStyle: { color: '#F56C6C' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(245, 108, 108, 0.3)' },
            { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
          ]
        }
      }
    }]
  });
};

// 新增：KPI卡片趋势图的独立数据
const generateKPITrendData = () => {
  // 生成KPI卡片中趋势图的独立数据（固定为今日时间段）
  const timeSegments = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00'];
  const inboundData = generateTimeSegmentData(6, 30, 20);
  const outboundData = generateTimeSegmentData(6, 25, 15);
  
  return {
    timeSegments,
    inboundData,
    outboundData
  };
};

// 新增：更新KPI卡片趋势图的函数
const updateKPITrendCharts = () => {
  const kpiData = generateKPITrendData();
  
  // 更新入库折线图
  if (inboundChart) {
    inboundChart.setOption({
      xAxis: { data: kpiData.timeSegments },
      series: [{
        data: kpiData.inboundData
      }]
    });
  }
  
  // 更新出库折线图
  if (outboundChart) {
    outboundChart.setOption({
      xAxis: { data: kpiData.timeSegments },
      series: [{
        data: kpiData.outboundData
      }]
    });
  }
};

// 生命周期
onMounted(() => {
  // 初始化图表
  initCharts();
  
  // 初始化详细数据
  updateDetailDataByDateRange();
  
  // 初始化员工打包统计图表
  setTimeout(() => {
    handleEmployeeDateChange();
  }, 100);
  
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理事件监听器和定时器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 清理实时数据更新定时器
  // if ((window as any).realTimeTimer) { // 删除这行
  //   clearInterval((window as any).realTimeTimer); // 删除这行
  // } // 删除这行
  
  // 销毁图表实例
  // if (pieChart) pieChart.dispose(); // 删除这行
  if (lineChart) lineChart.dispose();
  if (barChart) barChart.dispose();
  if (inboundChart) inboundChart.dispose();
  if (outboundChart) outboundChart.dispose();
  if (employeeChart) employeeChart.dispose();
});

// 处理窗口大小变化
const handleResize = () => {
  // if (pieChart) pieChart.resize(); // 删除这行
  if (lineChart) lineChart.resize();
  if (barChart) barChart.resize();
  if (inboundChart) inboundChart.resize();
  if (outboundChart) outboundChart.resize();
  if (employeeChart) employeeChart.resize();
};

const getLocationTypeTagType = (type: string) => {
  switch (type) {
    case '普通库位':
      return 'success';
    case '冷库':
      return 'info';
    case '危险品库位':
      return 'danger';
    default:
      return 'info';
  }
};

const getLocationStatusTagType = (status: string) => {
  switch (status) {
    case '可用':
      return 'success';
    case '占用':
      return 'warning';
    case '锁定':
      return 'info';
    case '禁用':
      return 'danger';
    default:
      return 'info';
  }
};

// 新增：获取物流方式颜色的函数
const getLogisticColor = (logistic: string) => {
  switch (logistic) {
    case '日本邮政EMS':
      return '#409EFF'; // 蓝色
    case '航空':
      return '#67C23A'; // 绿色
    case '海运':
      return '#E6A23C'; // 橙色
    case 'DHL':
      return '#F56C6C'; // 红色
    default:
      return '#909399'; // 灰色
  }
};

// 获取渠道颜色
const getChannelColor = (channel: string) => {
  const colors: { [key: string]: string } = {
    '日本邮政EMS': '#5470c6',
    '航空': '#91cc75',
    '海运': '#fac858',
    'DHL': '#ee6666',
    '日本国内': '#73c0de',
    '直通': '#3ba272',
    '直邮': '#fc8452'
  };
  return colors[channel] || '#5470c6';
};

// 分页相关方法
const handleDetailPageChange = (newPage: number) => {
  detailPage.value.current = newPage;
};

const handleDetailPageSizeChange = (newSize: number) => {
  detailPage.value.size = newSize;
  detailPage.value.current = 1; // 切换每页大小时重置当前页为1
};

// 图表时间单位切换处理
const handleChartTimeUnitChange = (unit: string) => {
  chartTimeUnit.value = unit;
  handleChartDateChange();
};

const handleShipmentTimeUnitChange = (unit: string) => {
  shipmentTimeUnit.value = unit;
  handleShipmentDateChange();
};

// 生成员工打包工作量数据
const generateEmployeeWorkloadData = (startDate: string, endDate: string) => {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const data: any[] = [];
  
  let current = new Date(start);
  while (current <= end) {
    const month = current.getMonth() + 1;
    const date = current.getDate();
    
    // 为每个员工生成数据
    packagers.forEach(packager => {
      const japanPostEMS = Math.floor(Math.random() * 50) + 10;
      const dhl = Math.floor(Math.random() * 30) + 5;
      const airFreight = Math.floor(Math.random() * 40) + 8;
      const seaFreight = Math.floor(Math.random() * 25) + 3;
      const japanDomestic = Math.floor(Math.random() * 35) + 6;
      const direct = Math.floor(Math.random() * 20) + 4;
      const directMail = Math.floor(Math.random() * 45) + 12;
      
      data.push({
        date: `${month}月${date}日`,
        packager,
        japanPostEMS,
        dhl,
        airFreight,
        seaFreight,
        japanDomestic,
        direct,
        directMail
      });
    });
    
    current.setDate(current.getDate() + 1);
  }
  
  return data;
};

// 员工打包统计图表实例
let employeeChart: echarts.ECharts | null = null;

// 处理员工打包统计日期变化
const handleEmployeeDateChange = () => {
  if (employeeDateRange.value && employeeDateRange.value.length === 2) {
    const data = generateEmployeeWorkloadData(employeeDateRange.value[0], employeeDateRange.value[1]);
    
    // 按员工汇总各渠道数据
    const employeeData: { [key: string]: any } = {};
    data.forEach(item => {
      if (!employeeData[item.packager]) {
        employeeData[item.packager] = {
          japanPostEMS: 0,
          dhl: 0,
          airFreight: 0,
          seaFreight: 0,
          japanDomestic: 0,
          direct: 0,
          directMail: 0
        };
      }
      employeeData[item.packager].japanPostEMS += item.japanPostEMS;
      employeeData[item.packager].dhl += item.dhl;
      employeeData[item.packager].airFreight += item.airFreight;
      employeeData[item.packager].seaFreight += item.seaFreight;
      employeeData[item.packager].japanDomestic += item.japanDomestic;
      employeeData[item.packager].direct += item.direct;
      employeeData[item.packager].directMail += item.directMail;
    });
    
    // 定义渠道颜色
    const channelColors = {
      japanPostEMS: '#5470c6',
      dhl: '#91cc75',
      airFreight: '#fac858',
      seaFreight: '#ee6666',
      japanDomestic: '#73c0de',
      direct: '#3ba272',
      directMail: '#fc8452'
    };
    
    const option = {
      title: {
        text: '员工打包工作量统计',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params: any) {
          let result = params[0].name + '<br/>';
          let total = 0;
          
          params.forEach((param: any) => {
            result += param.marker + param.seriesName + ': ' + param.value + '件<br/>';
            total += param.value;
          });
          
          result += '<hr/>总计: ' + total + '件';
          return result;
        }
      },
      legend: {
        data: ['日本邮政EMS', 'DHL', '航空', '海运', '日本国内', '直通', '直邮'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: Object.keys(employeeData),
        axisLabel: {
          rotate: 0
        }
      },
      yAxis: {
        type: 'value',
        name: '打包数量(件)'
      },
      series: [
        {
          name: '日本邮政EMS',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.japanPostEMS),
          itemStyle: { color: channelColors.japanPostEMS }
        },
        {
          name: 'DHL',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.dhl),
          itemStyle: { color: channelColors.dhl }
        },
        {
          name: '航空',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.airFreight),
          itemStyle: { color: channelColors.airFreight }
        },
        {
          name: '海运',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.seaFreight),
          itemStyle: { color: channelColors.seaFreight }
        },
        {
          name: '日本国内',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.japanDomestic),
          itemStyle: { color: channelColors.japanDomestic }
        },
        {
          name: '直通',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.direct),
          itemStyle: { color: channelColors.direct }
        },
        {
          name: '直邮',
          type: 'bar',
          stack: 'total',
          data: Object.values(employeeData).map(item => item.directMail),
          itemStyle: { color: channelColors.directMail }
        }
      ]
    };
    
    if (employeeChart) {
      employeeChart.setOption(option);
    } else {
      // 获取员工打包统计图表的容器 - 使用独特的类名
      const employeeChartRef = document.querySelector('.employee-chart-container') as HTMLElement;
      if (employeeChartRef) {
        employeeChart = echarts.init(employeeChartRef);
        employeeChart.setOption(option);
      }
    }
  }
};
</script>

<style scoped>
.warehouse-data-page { 
  padding: 24px; 
  background: #f7f8fa; 
  min-height: 100vh; 
}

.mb-3 { 
  margin-bottom: 24px; 
}

.search-panel {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.search-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.kpi-chart {
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

/* 库位使用率样式 */
.utilization-info {
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.utilization-progress {
  margin-bottom: 16px;
}

.progress-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 4px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #67C23A, #85CE61);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-value {
  font-size: 14px;
  font-weight: 600;
  color: #67C23A;
  text-align: right;
}

.utilization-stats {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-label {
  font-size: 10px;
  color: #999;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 异常情况统计样式 */
.exception-stats {
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.exception-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.exception-label {
  font-size: 11px;
  color: #666;
  flex: 1;
}

.exception-value {
  font-size: 14px;
  font-weight: 600;
  color: #F56C6C;
  text-align: right;
  min-width: 30px;
}

.kpi-chart-placeholder {
  height: 116px; /* 精确匹配：图表100px + 上边距16px */
  width: 100%;
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  box-sizing: border-box;
}

.kpi-title { 
  font-size: 14px; 
  color: #888; 
}

.kpi-value { 
  font-size: 28px; 
  font-weight: bold; 
  margin-top: 8px; 
  color: #303133;
}

.kpi-subtitle {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.chart-title { 
  font-size: 16px; 
  font-weight: bold; 
  margin-bottom: 8px; 
  color: #303133;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-controls .el-radio-group {
  margin-left: 8px;
}

.chart-controls .el-radio-button__inner {
  padding: 8px 16px;
  font-size: 12px;
  border-radius: 4px;
}

.chart-card {
  margin-bottom: 16px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.employee-chart-container {
  height: 300px;
  width: 100%;
}

.detail-table {
  background: #fff;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h4 {
  margin: 0;
  color: #303133;
}

.data-summary {
  font-size: 14px;
  color: #909399;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.utilization-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.utilization-bar {
  width: 100px;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.utilization-fill {
  height: 100%;
  background: linear-gradient(90deg, #67C23A, #85CE61);
  border-radius: 4px;
  transition: width 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-controls {
    justify-content: center;
  }
  
  .warehouse-data-page {
    padding: 16px;
  }
}
</style> 